package cn.qiuyu.gift.exception;



import cn.qiuyu.gift.enums.SystemErrorCode;
import cn.qiuyu.gift.util.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/*
当Controller里面发送的异常的时候此处做拦截
 */
//@ControllerAdvice
//@ResponseBody
@RestControllerAdvice
public class GlobalExceptionHandler {


    /*
        要捕获的异常类型是Exception  --包含子类
        如果当前的类里面对某一个子类做了单独的捕获就不走此处

     */
    @ExceptionHandler(Exception.class)
    public AjaxResult systemException(Exception e){
        e.printStackTrace();
        return AjaxResult.error(SystemErrorCode.RESPONSE_CODE_500);
    }
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult connectionTimeOut(RuntimeException e){
        e.printStackTrace();
        return AjaxResult.error(SystemErrorCode.RESPONSE_CODE_500007);
    }

    /*
        捕获业务异常

     */
    @ExceptionHandler(cn.qiuyu.gift.exception.BusinessException.class)
    public AjaxResult businessException(cn.qiuyu.gift.exception.BusinessException businessException){
        return AjaxResult.error(businessException.getSystemErrorCode());
    }


    /*
        JSR303校验:
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult validException(MethodArgumentNotValidException e){
        //e.getBindingResult().getAllErrors().get(0).getDefaultMessage()
        //拼接错误信息的对象
        StringBuffer buffer = new StringBuffer();
        //获取所有的错误信息
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        for (int i = 0; i < allErrors.size(); i++) {
            //具体的一个错误
            ObjectError error = allErrors.get(i);
            //获取错误信息
            String message = error.getDefaultMessage();
            //拼接错误信息
            if (i == allErrors.size()-1){
                buffer.append(message);
            }else {
                buffer.append(message).append(",");
            }

        }
        //把错误的提示信息返回给用户 错误码还是400
        return AjaxResult.error(SystemErrorCode.RESPONSE_CODE_400.setMsg(buffer.toString()));
    }


}
